package com.zyx.javademo.nio.chat.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zyx
 * @since 2021/9/18 15:49
 * desc: 客户端线程
 */
public class ClientThread implements Runnable {

    private final Selector selector;

    public ClientThread(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        // 5.循环，等待有新链接接入
            try {
                for (; ; ) {
                    // 获取channel数量
                    int readChannels = selector.select();
                    if (readChannels == 0) {
                        continue;
                    }

                    // 获取可用的chaneel
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    // 遍历集合
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();

                        // 移除set集合当前selectonKey
                        iterator.remove();

                        // 6.根据就绪状态调用对应方法实现具体业务操作
                        // 6.1 如果accept状态
                        // 6.2 如果可读状态
                        if (selectionKey.isReadable()) {
                            readOperator(selector, selectionKey);
                        }
                    }
                }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理可读状态操作
     */
    private void readOperator(Selector selector,
                              SelectionKey selectionKey) throws IOException {
        // 1.从selectionKey中获取已经就绪的通道
        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();

        // 2.创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 3.循环读取客户端消息
        int readLength = socketChannel.read(byteBuffer);
        StringBuilder message = new StringBuilder();

        while (readLength > 0) {
            // 切换读模式
            byteBuffer.flip();

            // 读取内容
            message.append(StandardCharsets.UTF_8.decode(byteBuffer));
            readLength = socketChannel.read(byteBuffer);

        }

        // 4.将channel再次注册到选择器上, 监听可读状态
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 5.把客户端发送消息, 广播到其他客户端
        if (message.length() > 0) {
            System.out.println(message);
        }
    }
}
